var app = getApp()

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')

const wxMap = new QQMapWX({
  key: 'NSUBZ-2GEKP-AYYDK-LMZXC-KE2LO-46B6H'
})
Page({
  data: {
    istokenPop: false, //判断是否等了
    isHas: false,
    shipType: 1,  //邮寄地址 1 自送 2
    openSet: false,

    list: [],

    allScore: 0,

    bookList: [], //添加书籍列表

    locationName: "未定位",

    showCon: false,

    localNum: 0, //附近收书点数量


    //没有书籍

    popOpen: false,
    isbnCode: '',

    list: [],


    expectedScore: 0,//预估书币
  },
  //邮寄配送选择
  tabClick(e) {
    console.log(e.currentTarget.dataset.type)
    const type = e.currentTarget.dataset.type
    this.setData({
      shipType: type
    })

    if (this.data.shipType == 2) {
      this.loactionInfo()
    }
  },

  // 点击下一步
  goaddLocation() {

    if (this.data.bookList.length == 0) {
      wx.showToast({
        title: '请添加书籍',
        icon: 'none'
      })
      return
    }

    var bookInfoIds = ''

    if (this.data.bookList.length == 1) {
      bookInfoIds = this.data.bookList[0].bookInfoId
    } else {
      for (var i = 0; i < this.data.bookList.length; i++) {
        bookInfoIds += this.data.bookList[i].bookInfoId + ','
      }

      if (bookInfoIds.length > 0) {
        bookInfoIds = bookInfoIds.substr(0, bookInfoIds.length - 1)
      }
    }

    // console.log(this.data.bookList[0].id)
    console.log(bookInfoIds)

    if (this.data.wasActivities == 1) {
      wx.navigateTo({
        url: '/package/juanshu/pages/addYouji/addYouji?bookInfoIds=' + bookInfoIds + '&shipType=' + this.data.shipType + '&bookLength=' + this.data.bookList.length + '&allScore=' + this.data.allScore + '&wasActivities=' + this.data.wasActivities,
      })
    } else {
      wx.navigateTo({
        url: '/package/juanshu/pages/addYouji/addYouji?bookInfoIds=' + bookInfoIds + '&shipType=' + this.data.shipType + '&bookLength=' + this.data.bookList.length + '&allScore=' + this.data.allScore,
      })
    }
  },

  //查看收书点
  nearShop() {
    if (this.data.bookList.length == 0) {
      wx.showToast({
        title: '请添加书籍',
        icon: 'none'
      })
      return
    }

    var bookInfoIds = ''

    if (this.data.bookList.length == 1) {
      bookInfoIds = this.data.bookList[0].id
    } else {
      for (var i = 0; i < this.data.bookList.length; i++) {
        bookInfoIds += this.data.bookList[i].id + ','
      }

      if (bookInfoIds.length > 0) {
        bookInfoIds = bookInfoIds.substr(0, bookInfoIds.length - 1)
      }
    }

    console.log(this.data.bookList[0].id)
    console.log(bookInfoIds)
    wx.navigateTo({
      url: '/package/juanshu/pages/nearShop/nearShop?localname=' + this.data.locationName + '&lat=' + this.data.latitude + '&long=' + this.data.longitude + '&bookInfoIds=' + bookInfoIds + '&shipType=' + this.data.shipType + '&fromType=1',
    })
  },

  //继续添书
  contentBook() {
    wx.navigateTo({
      url: '/package/juanshu/pages/saoma/saoma',
    })
  },



  //获取定位信息
  loactionInfo() {
    var _this = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        if (res.errMsg == 'getLocation:ok') {
          _this.setData({
            showCon: false,
            latitude: res.latitude,
            longitude: res.longitude
          })

          wx.removeStorageSync('lat')
          wx.removeStorageSync('long')
          wx.setStorageSync('lat', res.latitude)
          wx.setStorageSync('long', res.longitude)

          _this.getLocationName(res.latitude, res.longitude)
        }
      },
      fail: function (error) {
        _this.setData({
          showCon: true
        })
      }
    })
  },


  //接口部分
  //提供给下一个页面使用
  addBook() {


    this.getMyjuanshuListall()
    // var arr = this.data.bookList
    // var allScore = this.data.allScore

    // if (params.price == 0 || params.price=='') {
    //   debugger
    //   return
    // }

    // for (var i = 0;i< arr.length;i++) {
    //   if (arr[i].isbn == params.isbn) {
    //     wx.showToast({
    //       title: '不能重复添加同一本书',
    //       icon: 'none'
    //     })
    //     return
    //   }
    // }
    // arr.push(params)
    // allScore += params.maximumDiscount
    // this.setData({
    //   bookList: arr,
    //   allScore: allScore
    // })
  },

  //取消设置弹框
  changeModalCancel() {
    this.setData({
      showCon: false
    })
  },
  openSetting2(e) {
    console.log(e)
    if (e.detail.authSetting["scope.userLocation"]) {
      this.loactionInfo()
    } else {
      wx.showToast({
        title: '未设置',
        icon: 'none'
      })
    }
  },

  //wxMap获取地理位置

  getLocationName(latitude, longitude) {
    wx.showLoading({
      title: '定位中',
      mask: true
    })
    var _this = this
    wxMap.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res)
        if (res.message == 'query ok') {
          wx.hideLoading()
          _this.setData({
            locationName: res.result.address_component.city
          })
          wx.removeStorageSync('locationName')
          wx.setStorageSync('locationName', res.result.address_component.city)
          _this.getHuishouList(latitude, longitude, res.result.address_component.city)
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '定位失败',
          icon: 'none'
        })
      }
    })
  },


  //获取书籍回收驿站列表

  getHuishouList(latitude, longitude, city) {
    var _this = this
    var params = {
      pageNum: 1,
      pageSize: 999999,
      city: city,
      latitude: latitude,
      longitude: longitude
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/sdxBookStation/list/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          _this.setData({
            localNum: res.data.data.resultList.length
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },


  onLoad(options) {


    wx.setNavigationBarTitle({
      title: options.wasActivities == 1 ? '捐书给书濑熊' : '卖书给书濑熊'
    })


    if (options.wasActivities == 1) {
      this.setData({
        wasActivities: options.wasActivities
      })

    }

    if (options.bookInfoIds) {
      this.setData({
        isHas: true,
        bookList: JSON.parse(options.bookInfoIds)
      })

      // var allScore
      var score = this.data.allScore
      for (var i = 0; i < this.data.bookList.length; i++) {
        score += this.data.bookList[i].maximumDiscount
      }
      this.setData({
        allScore: score
      })

      console.log(this.bookInfoIds)
    } else {
      this.setData({
        isHas: false,
        allScore: 0
      })
    }
  },



  clearList() {
    this.setData({
      bookList: []
    })
  },


  detelesList(e) {
    var bookid = e.currentTarget.dataset.bookid



    this.deteleApi(bookid)
    // var sore = e.currentTarget.dataset.sore
    // var arr = this.data.bookList
    // var allsore = this.data.allScore
    // var allScore = this.data.allScore
    // for (var i = 0;i< arr.length; i++) {
    //   if (bookid == arr[i].id) {
    //     arr.splice(i,1)
    //     allScore -= sore
    //   }
    // }

    // this.setData({
    //   bookList: arr
    // })
  },

  deteleApi(shopid) {

    var _this = this
    wx.showLoading({
      title: '删除中',
      icon: 'none'
    })
    var params = {
      id: shopid
    }
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/delWasUpAdmin/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading()

          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })
          var arr = _this.data.bookList

          var allScore = _this.data.allScore
          for (var i = 0; i < arr.length; i++) {
            if (shopid == arr[i].id) {
              allScore -= arr[i].maxScore
              arr.splice(i, 1)
            }
          }
          _this.setData({
            bookList: arr,
            allScore: allScore
          })
        }
      }
    })
  },


  //扫码卖书


  getScancode() {

    if (wx.getStorageSync('token') == '') {
      this.setData({
        istokenPop: true
      })
      return
    }
    var _this = this
    wx.scanCode({
      success: (res) => {
        console.log(res)
        if (res.errMsg == 'scanCode:ok') {
          wx.showToast({
            title: '扫码成功',
            icon: 'none'
          })
          var params = {
            isbnCode: res.result
          }
          if (_this.data.wasActivities == 1) {
            params.wasActivities = 1
          }
          _this.getBookuser(params)
        } else {
          wx.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      }
    })
  },

  getBookuser(params) {
    var _this = this
    wx.showLoading({
      title: '书本信息获取中',
      mask: true
    })
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/donate/getBookInfo/auth',
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {

        if (res.data.code == 200) {

          // wx.showLoading()
          // if (res.data.data != '' && res.data.data.price != 0 && res.data.data.price != '' && res.data.data.price != null && res.data.data.price != undefined) {
          wx.showToast({
            title: '添加成功',
            icon: 'none',
            duration: 2000
          })


          setTimeout(function () {
            _this.setData({
              popOpen: false
            })


            var params = {
              id: res.data.data.id,
              name: res.data.data.name,
              serviceId: res.data.data.serviceId,
              author: res.data.data.author,
              price: res.data.data.price,
              coverPic: res.data.data.coverPic,
              maximumDiscount: res.data.data.expectedScore,
              isbn: res.data.data.isbn
            }
            // var pages = getCurrentPages()
            // var beforePage = pages[pages.length - 2]


            _this.addBook()
          }, 2000)



          // } else {
          //   wx.navigateTo({
          //     url: '/package/juanshu/pages/shibieJieguo/shibieJieguo',
          //   })
          // }
        } else {

          wx.navigateTo({
            url: '/package/juanshu/pages/shibieJieguo/shibieJieguo',
          })
          // wx.showToast({
          //   title: res.data.msg,
          //   icon: 'none'
          // })
        }
        // console.log(res)
      }
    })
  },



  //没有书籍

  popOpen() {
    this.setData({
      popOpen: true
    })
  },
  // 关闭弹窗
  closePop() {
    this.setData({
      popOpen: false
    })
  },



  // 手动输入bn吗
  bindCode(e) {
    this.setData({
      isbnCode: e.detail.value
    })
  },



  //获取添加列表


  getMyjuanshuListall() {


    var params = {}

    if (this.data.wasActivities == 1) {
      params.wasActivities = 1
    }

    wx.showLoading({
      title: '书籍加载中',
      icon: 'none'
    })
    var _this = this
    wx.request({
      url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/book/findAdminBookInfo/auth',
      method: 'POST',
      data: params,
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading()
          _this.setData({
            bookList: res.data.data.resultList,
            allScore: res.data.data.expectedScore
          })
        }
      }
    })
  },

  //

  sureAddbook() {
    var reg = /^[0-9]*$/
    if (this.data.isbnCode == '') {
      wx.showToast({
        title: 'ISBN码不能为空',
        icon: 'none'
      })
      return
    }

    if (!reg.test(this.data.isbnCode)) {
      wx.showToast({
        title: '请输入数字',
        icon: 'none'
      })
      return
    }

    // if 

    if (this.data.isbnCode.length != 13) {
      wx.showToast({
        title: '请输入正确isbn',
        icon: 'none'
      })
      return
    }

    var params = {
      isbnCode: this.data.isbnCode
    }

    if (this.data.wasActivities == 1) {
      params.wasActivities = 1
    }
    this.getBookuser(params)
  },



  //跳转信息修改
  goChangeXinxi(e) {
    var bookInfoid = e.currentTarget.dataset.bookid
    wx.navigateTo({
      url: '/package/juanshu/pages/goChangeXinxi/goChangeXinxi?bookInfoId=' + bookInfoid,
    })
  },


  lookMore () {
    wx.navigateTo({
      url: '/package/juanshu/pages/buyRoule/buyRoule',
    })
  },


  //获取卖款播报
  getList() {


    var params = {
      page: 1,
      size: 5
    }

    var _this = this
    var url='https://devapi.xiaoshitimebank.com/user/sdx/sdx/user/global/donate'
    wx.request({
      url: url,
      data: params,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "token": wx.getStorageSync('token'),
        "uid": wx.getStorageSync('uuid')
      },
      success: (res) => {
        if (res.data.code == 200) {
          var arr = res.data.data
          _this.setData({
            list: arr
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },



  //取消弹框
  touchMove() {
    this.setData({
      istokenPop: true
    })
  },


  loginCode() {
    this.setData({
      istokenPop: false
    })

    // this.onLoad()
    this.onShow()
  },


  onShow() {


    app.getUserset()

    this.getList()
    if (wx.getStorageSync('token')!='') {
      this.getMyjuanshuListall()
    }
  },


  //接口

  // 手动输入
  // getBookuser(params) {
  //   var _this = this
  //   wx.request({
  //     url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/order/donate/getBookInfo/auth',
  //     data: params,
  //     method: 'POST',
  //     header: {
  //       "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
  //       "token": wx.getStorageSync('token'),
  //       "uid": wx.getStorageSync('uuid')
  //     },
  //     success: (res) => {

  //       if (res.data.code == 200) {

  //         if (res.data.data != '' && res.data.data.price != 0 && res.data.data.price != '' && res.data.data.price != null && res.data.data.price != undefined) {

  //           wx.showToast({
  //             title: '添加成功',
  //             icon: 'none',
  //             duration: 1000
  //           })
  //           _this.setData({
  //             popOpen: false
  //           })

  //             var params = {
  //               id: res.data.data.id,
  //               name: res.data.data.name,
  //               serviceId: res.data.data.serviceId,
  //               author: res.data.data.author,
  //               price: res.data.data.price,
  //               coverPic: res.data.data.coverPic,
  //               maximumDiscount: res.data.data.expectedScore
  //             }
  //           _this.addBook(params)
  //         } else {
  //           wx.navigateTo({
  //             url: '/package/juanshu/pages/shibieJieguo/shibieJieguo',
  //           })
  //         }
  //       } else {
  //         wx.showToast({
  //           title: res.data.msg,
  //           icon: 'none'
  //         })
  //       }
  //       // console.log(res)
  //     }
  //   })
  // }

  // onShow () {
  //   if (this.data.bookList.length == 0) {
  //     wx.navigateTo({
  //       url: '/package/juanshu/pages/saoma/saoma',
  //     })
  //   }else{
  //     return false
  //   }
  // }
})
